package com.jeecg.demo.controller;
import com.jeecg.demo.entity.VolumeEntity;
import com.jeecg.demo.service.VolumeServiceI;
import java.util.ArrayList;
import java.util.List;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;


/**   
 * @Title: Controller  
 * @Description: 成交信息录入
 * @author onlineGenerator
 * @date 2018-11-19 14:41:01
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/volumeController")
public class VolumeController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(VolumeController.class);

	@Autowired
	private VolumeServiceI volumeService;
	@Autowired
	private SystemService systemService;
	


	/**
	 * 成交信息录入列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/demo/volumeList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(VolumeEntity volume,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(VolumeEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, volume, request.getParameterMap());
		String ctBegin = request.getParameter("createTime_begin");  
		 String ctEnd = request.getParameter("createTime_end");  
		 if(StringUtil.isNotEmpty(ctBegin)&& StringUtil.isNotEmpty(ctEnd)){
			 try{
				 //自定义追加查询条件
				 cq.ge("createTime", new SimpleDateFormat("yyyy-MM-dd").parse(ctBegin));  
				 cq.le("createTime", new SimpleDateFormat("yyyy-MM-dd").parse(ctEnd));  
			 }catch (Exception e) {
				 throw new BusinessException(e.getMessage());
			 }
			 cq.add();
		 }
		this.volumeService.getDataGridReturn(cq, true);
		
		//update-begin--Author:zhaojunfu  Date:20130520 for：TASK #109 datagrid标签没有封装合计功能
		String total = String.valueOf(volumeService.findOneForJdbc("select sum(turnover) as ssum from  VOLUME").get("ssum"));  
		String price = String.valueOf(volumeService.findOneForJdbc("select sum(volumeprice) as price from VOLUME").get("price"));  
		/*
		* 说明：格式为 字段名:值(可选，不写该值时为分页数据的合计) 多个合计 以 , 分割
		*/
		String unit="千克";
		String unit1="元";
		DecimalFormat df = new DecimalFormat("#.##");
		Double tt = Double.valueOf(total);
		Double pp = Double.valueOf(price);
		Double tp=tt*pp;
		if (tt>=1000) {
			unit="吨";
			tt=tt/1000;
		}
		//update-end--Author:zhaojunfu  Date:20130520 for：TASK #109 datagrid标签没有封装合计功能
		if (tp>=10000&tp<100000000) {
			unit1="万元";
			tp=tp/10000;
		}	
		if (tp>=100000000) {
			unit1="亿";
			tp=tp/100000000;
		}
		dataGrid.setFooter("turnover:"+df.format(tt)+unit+",age,seller:合计,variety:"+df.format(tp)+unit1+",age,volumeprice:"+"总金额");
		
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除成交信息录入
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(VolumeEntity volume, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		volume = systemService.getEntity(VolumeEntity.class, volume.getId());
		message = "删除成功";
		try{
			volumeService.delete(volume);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除成交信息录入
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "删除成功";
		try{
			for(String id:ids.split(",")){
				VolumeEntity volume = systemService.getEntity(VolumeEntity.class, 
				Integer.parseInt(id)
				);
				volumeService.delete(volume);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加成交信息录入
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(VolumeEntity volume, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "添加成功";
		try{
			volumeService.save(volume);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新成交信息录入
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(VolumeEntity volume, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "更新成功";
		VolumeEntity t = volumeService.get(VolumeEntity.class, volume.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(volume, t);
			volumeService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 成交信息录入新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(VolumeEntity volume, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(volume.getId())) {
			volume = volumeService.getEntity(VolumeEntity.class, volume.getId());
			req.setAttribute("volumePage", volume);
		}
		return new ModelAndView("com/jeecg/demo/volume-add");
	}
	/**
	 * 成交信息录入编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(VolumeEntity volume, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(volume.getId())) {
			volume = volumeService.getEntity(VolumeEntity.class, volume.getId());
			req.setAttribute("action", "volumeController.do?doUpdate");
			req.setAttribute("volumePage", volume);
		}
		return new ModelAndView("com/jeecg/demo/volume-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","volumeController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(VolumeEntity volume,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(VolumeEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, volume, request.getParameterMap());
		List<VolumeEntity> volumes = this.volumeService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"成交信息录入");
		modelMap.put(NormalExcelConstants.CLASS,VolumeEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("成交信息录入列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,volumes);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(VolumeEntity volume,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"成交信息录入");
    	modelMap.put(NormalExcelConstants.CLASS,VolumeEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("成交信息录入列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<VolumeEntity> listVolumeEntitys = ExcelImportUtil.importExcel(file.getInputStream(),VolumeEntity.class,params);
				for (VolumeEntity volume : listVolumeEntitys) {
					volumeService.save(volume);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(e.getMessage());
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
}
